package main

import (
	"api/auth"
	"api/common"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
)

func main() {
	serverID := "c12cfb90-9e97-4a84-8da8-566627055f0f"
	url := fmt.Sprintf("https://api.saltyun.com:30888/servers/%s/metadata", serverID)

	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	client := &http.Client{Transport: tr}

	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Fatalf("构建请求失败: %v", err)
	}

	token, err := auth.GetToken("sysadmin", "N48XSRmcsP5YMcPf")
	if err != nil {
		log.Fatalf("获取 Token 失败: %v", err)
	}
	req.Header.Set("X-Auth-Token", token)
	req.Header.Set("Accept", "application/json")

	res, err := client.Do(req)
	if err != nil {
		log.Fatalf("请求失败: %v", err)
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		log.Fatalf("读取响应失败: %v", err)
	}

	//fmt.Println("body:", string(body))
	common.OutputJson(string(body))

	var result struct {
		Metadata map[string]interface{} `json:"metadata"`
	}

	if err := json.Unmarshal(body, &result); err != nil {
		log.Fatalf("解析 JSON 失败: %v", err)
	}

	fmt.Println("虚拟机元数据:")
	for k, v := range result.Metadata {
		fmt.Printf("  %s: %v\n", k, v)
	}

	if pwd, ok := result.Metadata["password"].(string); ok {
		fmt.Println("明文密码:", pwd)
	} else {
		fmt.Println("未找到明文密码字段 password（说明可能未配置或被隐藏）")
	}
}
